import xml.dom.minidom
import xml.dom.ext
import os
import sys

# load a document from path
def load_document(path):
    return xml.dom.minidom.parse(path)

doc = load_document("/var/www/program_table.xml")

def add_program(filename, name, desc):
    list = doc.getElementsByTagName("program")
    maxi = 0 # highest id (for auto-increment)
    for x in list:
        if int(x.getAttribute("id")) >= maxi:
            maxi = int(x.getAttribute("id")) + 1 
    prog = doc.createElement("program")
    prog.setAttribute("id", str(maxi))
    elem = doc.createElement("name")
    elem.appendChild(doc.createTextNode(name))
    prog.appendChild(elem)
    elem = doc.createElement("description")
    elem.appendChild(doc.createTextNode(desc))
    prog.appendChild(elem)
    devs = doc.createElement("download_devices")
    # torrent
    devi = doc.createElement("device")
    devi.setAttribute("type", "torrent")
    prop = doc.createElement("property")
    prop.setAttribute("name", "torrent")
    prop.appendChild(doc.createTextNode("http://cowboycoders.se/torrents/" + filename + ".torrent"))
    devi.appendChild(prop)
    devs.appendChild(devi)
    os.system("./createtorrent -a http://cowboycoders.se:6969/announce " + filename + " /var/www/torrents/" + filename + ".torrent > /dev/null")
    # http
    devi = doc.createElement("device")
    devi.setAttribute("type", "http")
    prop = doc.createElement("property")
    prop.setAttribute("name", "address")
    prop.appendChild(doc.createTextNode("cowboycoders.se"))
    devi.appendChild(prop)
    prop = doc.createElement("property")
    prop.setAttribute("name", "port")
    prop.appendChild(doc.createTextNode("22234"))
    devi.appendChild(prop)
    prop = doc.createElement("property")
    prop.setAttribute("name", "file")
    prop.appendChild(doc.createTextNode(filename))
    devi.appendChild(prop)
    prop = doc.createElement("property")
    prop.setAttribute("name", "max_simultaneous_downloads")
    prop.appendChild(doc.createTextNode("3"))
    devi.appendChild(prop)
    devs.appendChild(devi)
    os.system("cp " + filename + " /home/cowboy/code/libcow/trunk/on_demand_server/docs/")
    # append to doc
    prog.appendChild(devs)
    doc.childNodes[1].appendChild(prog)

def pretty_print(doc):
    xml.dom.ext.PrettyPrint(doc)

if len(sys.argv) != 4:
    print "usage: python make_that_xml <filename> <name> <description>"
    sys.exit()
add_program(sys.argv[1], sys.argv[2], sys.argv[3])
pretty_print(doc)
